<template>
  <!-- 虚拟计划填报表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1300px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="150">
      <el-row>
        <el-col :span="8">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantId"
              placeholder="请输入工厂"
              clearable
              style="width: 400px"
              @change="changePlant"
              filterable
            >
              <el-option
                v-for="plant in plantList"
                :key="plant.id"
                :label="plant.organizationCode"
                :value="plant.id"
              />
            </el-select>
            <span v-else>{{ plantCode(formData.plantId) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作中心" prop="workCenterId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workCenterId"
              placeholder="请选择工作中心"
              clearable
              style="width: 300px"
              filterable
              @change="changeWorkCenter"
            >
              <el-option
                v-for="item in workCenterList"
                :key="item.id"
                :label="`${item.workshopCode}-${item.workshopName}`"
                :value="item.id"
              />
            </el-select>

            <span v-else
              >{{ formData.workCenterCode }}-{{ formData.workCenterName }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="加工单" prop="workOrderId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workOrderId"
              placeholder="请输入加工单"
              clearable
              style="width: 300px"
              filterable
              @change="changeWorkOrder"
            >
              <el-option
                v-for="item in workOrderList"
                :key="item.id"
                :label="`${item.workOrderCode}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.workOrderCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划数量" prop="planQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planQuantity"
              placeholder="请输入计划数量"
              clearable
              disabled
            />

            <span v-else>{{ formData.planQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已完成数量" prop="planFinishQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planFinishQuantity"
              placeholder="请输入已完成数量"
              clearable
              disabled
            />

            <span v-else>{{ formData.planFinishQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划年份" prop="planYear">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planYear"
              placeholder="请输入计划年份"
              clearable
              disabled
            />

            <span v-else>{{ formData.planYear }}</span>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="8">
          <el-form-item label="派工单" prop="workingFormId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workingFormId"
              placeholder="请输入加工单"
              clearable
              style="width: 300px"
              filterable
              @change="changeWorkingForm"
            >
              <el-option
                v-for="item in workingFormList"
                :key="item.id"
                :label="`${item.workingFormCode}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.workingFormCode }}</span>
          </el-form-item>
        </el-col>-->
        <el-col :span="8">
          <el-form-item label="日期/班次" prop="workingFormId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workingFormId"
              placeholder="请输入日期/班次"
              clearable
              style="width: 300px"
              filterable
              @change="changeWorkingForm"
            >
              <el-option
                v-for="item in workingFormList"
                :key="item.id"
                :label="`${item.planDate.split(' ')[0]}/${item.shiftName}`"
                :value="item.id"
              />
            </el-select>
            <span v-else
              >{{ formData.planDate.split(" ")[0] }}/{{
                formData.shiftName
              }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="派工单" prop="shiftName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.workingFormCode"
              placeholder="请输入计划班次"
              clearable
              disabled
            />

            <span v-else>{{ formData.workingFormCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="派工单计划数量" prop="workingPlanQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.workingPlanQuantity"
              placeholder="请输入派工单计划数量"
              clearable
              disabled
            />

            <span v-else>{{ formData.workingPlanQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划周数" prop="planWeek">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planWeek"
              placeholder="请输入计划周数"
              clearable
              disabled
            />

            <span v-else>{{ formData.planWeek }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="派工单已完成数量"
            prop="workingPlanFinishQuantity"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.workingPlanFinishQuantity"
              placeholder="请输入已完成数量"
              clearable
              disabled
            />

            <span v-else>{{ formData.workingPlanFinishQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合格数量" prop="validQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.validQuantity"
              placeholder="请输入合格数量"
              clearable
              disabled
            />

            <span v-else>{{ formData.validQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="不合格数量" prop="invalidQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.invalidQuantity"
              placeholder="请输入不合格数量"
              clearable
              disabled
            />

            <span v-else>{{ formData.invalidQuantity }}</span>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="8">
          <el-form-item label="计划班次" prop="shiftName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.shiftName"
              placeholder="请输入计划班次"
              clearable
              disabled
            />

            <span v-else>{{ formData.shiftName }}</span>
          </el-form-item>
        </el-col>-->
        <el-col :span="8">
          <el-form-item label="报工数量" prop="reportQuantity">
            <!--            <el-input-->
            <!--              v-if="!props.isReadonly"-->
            <!--              v-model="formData.reportQuantity"-->
            <!--              placeholder="请输入报工数量"-->
            <!--              clearable-->
            <!--            />-->
            <el-input-number
              v-if="!props.isReadonly"
              v-model="formData.reportQuantity"
              :min="1"
              style="width: 300px"
            />
            <span v-else>{{ formData.reportQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否合格" prop="isValid">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.isValid"
              placeholder="请选择是否合格"
              clearable
              style="width: 270px"
            >
              <el-option
                v-for="item in isValidList"
                :key="item.value"
                :label="`${item.label}`"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.isValid == 1 ? "合格" : "不合格" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="MMM DD, YYYY"
              time-format="HH:mm"
              style="width: 270px"
            />

            <span v-else>{{ formData.startTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="完工时间" prop="completeTime">
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.completeTime"
              type="datetime"
              placeholder="请选择完工时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="MMM DD, YYYY"
              time-format="HH:mm"
              style="width: 270px"
            />
            <span v-else>{{ formData.completeTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit(0)"
          >保 存</el-button
        >
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit(1)"
          >提 交</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESVIRTUALPLANREPORTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  plantId: [
    { required: true, message: "请输入工厂", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  workCenterId: [
    { required: true, message: "请输入工作中心", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  workOrderId: [
    { required: true, message: "请输入加工单", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  planQuantity: [],
  planFinishQuantity: [],
  planYear: [],
  planWeek: [],
  workingFormId: [
    { required: true, message: "请输入派工单", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  workingPlanQuantity: [],
  workingPlanFinishQuantity: [],
  validQuantity: [],
  invalidQuantity: [],
  shiftName: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  reportQuantity: [
    { required: true, message: "请输入报工数量", trigger: "blur" },
    // { pattern: /^[1-9]+$/, message: "请输入数字", trigger: "blur" },
  ],
  isValid: [{ required: true, message: "请输入是否合格", trigger: "change" }],
  startTime: [],
  completeTime: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  workOrderId: "",
  workOrderCode: "",
  planQuantity: "",
  planFinishQuantity: "",
  planYear: "",
  planWeek: "",
  workingFormId: "",
  workingFormCode: "",
  workingPlanQuantity: "",
  workingPlanFinishQuantity: "",
  validQuantity: "",
  invalidQuantity: "",
  planDate: "",
  shiftId: "",
  shiftName: "",
  workOrderPlanId: "",
  reportQuantity: 1,
  reportState: "",
  isValid: "",
  startTime: "",
  completeTime: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        workCenterName,
        workOrderId,
        workOrderCode,
        planQuantity,
        planFinishQuantity,
        planYear,
        planWeek,
        workingFormId,
        workingFormCode,
        workingPlanQuantity,
        workingPlanFinishQuantity,
        validQuantity,
        invalidQuantity,
        planDate,
        shiftId,
        shiftName,
        workOrderPlanId,
        reportQuantity,
        reportState,
        isValid,
        startTime,
        completeTime,
        remarks,
        version,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        workCenterName,
        workOrderId,
        workOrderCode,
        planQuantity,
        planFinishQuantity,
        planYear,
        planWeek,
        workingFormId,
        workingFormCode,
        workingPlanQuantity,
        workingPlanFinishQuantity,
        validQuantity,
        invalidQuantity,
        planDate,
        shiftId,
        shiftName,
        workOrderPlanId,
        reportQuantity,
        reportState,
        isValid,
        startTime,
        completeTime,
        remarks,
        version,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
    getWorkingFormList();
    getWorkOrderList();
    getWorkCenterList();
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  formData.workOrderId = "";
  formData.workOrderCode = "";
  formData.planQuantity = "";
  formData.planFinishQuantity = "";
  formData.planYear = "";
  formData.planWeek = "";
  formData.workingFormId = "";
  formData.workingFormCode = "";
  formData.workingPlanQuantity = "";
  formData.workingPlanFinishQuantity = "";
  formData.validQuantity = "";
  formData.invalidQuantity = "";
  formData.planDate = "";
  formData.shiftId = "";
  formData.shiftName = "";
  formData.workOrderPlanId = "";
  formData.reportQuantity = 1;
  formData.reportState = "";
  formData.isValid = "";
  formData.startTime = "";
  formData.completeTime = "";
  formData.remarks = "";
  formData.version = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 虚拟计划填报保存提交 */
function handleSubmit(state: Number) {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.reportState = state;
      await request({
        url: "/mes/mesvirtualplanreport/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
const changePlant = (id: any) => {
  workCenterList.value = [];
  workCenterClean();
  workOrderClean();
  workingFormClean();
  formData.plantId = id;
  formData.plantCode = plantCode(id);
  if (!id) {
  }
  getWorkCenterList();
};

// 工作中心
const workCenterList: any = ref([]);
const getWorkCenterList = async () => {
  if (formData.plantId != "") {
    const res: any = await request({
      url: `/mes/mesworkshop/getList`,
      method: "post",
      data: { enabled: 1, plantId: formData.plantId },
    });
    workCenterList.value = res.data;
  } else {
    // workCenterList.value = [];
    // formData.workCenterId = "";
    // formData.workCenterCode = "";
    // formData.workCenterName = "";
    workCenterClean();
    workOrderClean();
    workingFormClean();
  }
};
const changeWorkCenter = (id: any) => {
  workCenterClean();
  workOrderClean();
  workingFormClean();
  formData.workCenterId = id;
  workCenterList.value.forEach((item: any) => {
    if (item.id == id) {
      formData.workCenterCode = item.workshopCode;
      formData.workCenterName = item.workshopName;
    }
  });
  if (!id) {
  }
  getWorkOrderList();
};
// 加工单
const workOrderList: any = ref([]);
const getWorkOrderList = async () => {
  if (formData.workCenterId != "") {
    const res: any = await request({
      url: `/mes/mesworkorder/queryByWorkCenter`,
      method: "post",
      data: { workCenterId: formData.workCenterId },
    });
    workOrderList.value = res.data;
  } else {
    // workOrderList.value = [];
    // formData.workOrderId = "";
    // formData.workOrderCode = "";
    // formData.planQuantity = "";
    // formData.planFinishQuantity = "";
    // formData.planYear = "";
    // formData.planWeek = "";
    // workCenterClean();
    workOrderClean();
    workingFormClean();
  }
};
const changeWorkOrder = (id: any) => {
  workOrderClean();
  workingFormClean();
  formData.workOrderId = id;
  workOrderList.value.forEach((item: any) => {
    if (item.id == id) {
      formData.workOrderCode = item.workOrderCode;
      formData.planQuantity = item.planQuantity;
      formData.planFinishQuantity = item.planFinishQuantity;
      formData.planYear = item.planYear;
      formData.planWeek = item.planWeek;
    }
  });
  if (!id) {
    // formData.workOrderId = "";
    // formData.workOrderCode = "";
    // formData.planQuantity = "";
    // formData.planFinishQuantity = "";
    // formData.planYear = "";
    // formData.planWeek = "";
  }
  getWorkingFormList();
};

// 派工单
const workingFormList: any = ref([]);
const getWorkingFormList = async () => {
  if (formData.workOrderId != "") {
    const res: any = await request({
      url: `/mes/mesworkingform/getWorkingFormList`,
      method: "post",
      data: { workOrderId: formData.workOrderId },
    });
    workingFormList.value = res.data;
  } else {
    workingFormList.value = [];
    formData.workingFormId = "";
    formData.workingFormCode = "";
    formData.workingPlanQuantity = "";
    formData.workingPlanFinishQuantity = "";
    formData.validQuantity = "";
    formData.invalidQuantity = "";
    formData.planDate = "";
    formData.shiftId = "";
    formData.shiftName = "";
  }
};
const changeWorkingForm = (id: any) => {
  formData.workingFormId = id;
  workingFormList.value.forEach((item: any) => {
    if (item.id == id) {
      formData.workingFormCode = item.workingFormCode;
      formData.workingPlanQuantity = item.planQuantity;
      formData.workingPlanFinishQuantity = item.planFinishQuantity;
      formData.validQuantity = item.validQuantity;
      formData.invalidQuantity = item.invalidQuantity;
      formData.planDate = item.planDate;
      formData.shiftId = item.shiftId;
      formData.shiftName = item.shiftName;
    }
  });
  if (!id) {
    formData.workingFormId = "";
    formData.workingFormCode = "";
    formData.workingPlanQuantity = "";
    formData.workingPlanFinishQuantity = "";
    formData.validQuantity = "";
    formData.invalidQuantity = "";
    formData.planDate = "";
    formData.shiftId = "";
    formData.shiftName = "";
  }
};
const isValidList = ref([
  {
    label: "合格",
    value: 1,
  },
  {
    label: "不合格",
    value: 0,
  },
]);

function workCenterClean() {
  // workCenterList.value = [];
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  // formData.workOrderId = "";
  // formData.workOrderCode = "";
  // formData.planQuantity = "";
  // formData.planFinishQuantity = "";
  // formData.planYear = "";
  // formData.planWeek = "";
  // formData.workingFormId = "";
  // formData.workingFormCode = "";
  // formData.workingPlanQuantity = "";
  // formData.workingPlanFinishQuantity = "";
  // formData.validQuantity = "";
  workOrderList.value = [];
  workingFormList.value = [];
}
function workOrderClean() {
  // workOrderList.value = [];
  formData.workOrderId = "";
  formData.workOrderCode = "";
  formData.planQuantity = "";
  formData.planFinishQuantity = "";
  formData.planYear = "";
  formData.planWeek = "";
  workingFormList.value = [];
  // formData.workingFormId = "";
  // formData.workingFormCode = "";
  // formData.workingPlanQuantity = "";
  // formData.workingPlanFinishQuantity = "";
  // formData.validQuantity = "";
}
function workingFormClean() {
  // workingFormList.value = [];
  formData.workingFormId = "";
  formData.workingFormCode = "";
  formData.workingPlanQuantity = "";
  formData.workingPlanFinishQuantity = "";
  formData.validQuantity = "";
  formData.invalidQuantity = "";
  formData.planDate = "";
  formData.shiftId = "";
  formData.shiftName = "";
}

onMounted(() => {
  getPlantList();
});
</script>
